package org.linlinjava.litemall.wx.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.linlinjava.litemall.core.express.ExpressService;
import org.linlinjava.litemall.core.express.dao.ExpressInfo;
import org.linlinjava.litemall.core.express.dao.Traces;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 物流信息查询接口
 */
@RestController
@RequestMapping("/wx/express")
public class WxExpressController {

    private ExpressService expressService;

    public WxExpressController(ExpressService expressService) {
        this.expressService = expressService;
    }

    @PostMapping("query")
    public Object query(@LoginUser Integer userId, @RequestBody String body) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }

        String expCode = JacksonUtil.parseString(body, "expCode");
        String expNo = JacksonUtil.parseString(body, "expNo");
        String expName;
        if (expressService.isContainChinese(expCode)) {
            expName = expCode;
            expCode = expressService.getVendorCode(expCode);
        } else {
            expName = expressService.getVendorName(expCode);
        }
        try {
            String result = expressService.getOrderTracesByJson(expCode, expNo);

            ObjectMapper objMap = new ObjectMapper();
            ExpressInfo ei = objMap.readValue(result, ExpressInfo.class);
            List<Traces> traces = ei.getTraces();
            if(traces.size()>1) {
                Collections.reverse(traces);
                Map<String, Object> data = new HashMap<>(16);
                data.put("expCode", ei.getLogisticCode());
                data.put("expNo", ei.getShipperCode());
                data.put("expName", expName);
                data.put("Traces", traces);
                return ResponseUtil.ok(data);
            }else{
                return ResponseUtil.badArgument();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseUtil.badArgument();
    }
}
